package com.example.fragment;

import com.ab.view.listener.AbOnListViewListener;
import com.ab.view.pullview.AbPullListView;
import com.ab.view.pullview.AbPullView;
import com.example.activity.CaptureActivity;
import com.example.app.MyApplication;
import com.benchi.ncar.R;
import com.example.tools.ClearEditText;
import com.example.tools.Constants;
import com.example.tools.CustomProgressDialog;
import com.example.tools.IsNetWork;
import com.example.tools.Tools;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebView.FindListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public abstract class BaseFragment extends Fragment implements OnClickListener {
	protected ProgressDialog mProgressDialog;
	protected View mRootView = null;
	protected AbPullListView mAbPullListView = null;
	protected TextView mTvTitle;
	protected ImageView mImgBack;
	protected Builder mBialog;
	protected View mHeadView;
	protected WebView webview;
	protected String url;
	protected ClearEditText mEtSearch;
	protected RelativeLayout mRlHeadView;
	protected CustomProgressDialog mCustDialog;

	// @Override
	// public View onCreateView(LayoutInflater inflater, ViewGroup container,
	// Bundle savedInstanceState) {
	// if (mRootView == null) {
	// mRootView = inflater.inflate(R.layout.home, container, false);
	// ViewUtils.inject(this, mRootView);
	// initViews();
	// // super.showWaittingDialog();
	// }
	// ViewGroup parent = (ViewGroup) mRootView.getParent();
	// if (parent != null) {
	// parent.removeView(mRootView);
	// }
	// return mRootView;
	// }

	protected void initViews() {
		mRlHeadView = (RelativeLayout) mRootView
				.findViewById(R.id.rl_head_view);
		mEtSearch = (ClearEditText) mRootView.findViewById(R.id.et_clear);
		mEtSearch.setHandler(handler);
		mAbPullListView = (AbPullListView) mRootView
				.findViewById(R.id.lv_produce_detail);
		mAbPullListView.setPullRefreshEnable(true);
		mAbPullListView.setPullLoadEnable(false);
		mHeadView = LayoutInflater.from(getActivity()).inflate(
				R.layout.activity_webview, null);
		webview = (WebView) mRootView.findViewById(R.id.wb_home);
		// 设置WebView属性，能够执行Javascript脚本
		webview.getSettings().setJavaScriptEnabled(true);
		mAbPullListView.addHeaderView(mHeadView, null, true);
		mAbPullListView.setAdapter(null);
		mAbPullListView.setAbOnListViewListener(new AbOnListViewListener() {

			@Override
			public void onRefresh() {
				initData(url);
			}

			@Override
			public void onLoadMore() {
			}

		});
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				String content = mEtSearch.getText().toString();
				String url = "";
				if (content != null) {
					url = Constants.HOME_SEARCH + content;
				} else {
					url = Constants.HOME_URL;
				}
				initData(url);
				break;
			case 2:
				mAbPullListView.setVisibility(View.VISIBLE);
				webview.setVisibility(View.GONE);
				break;
			}

		};
	};

	protected void initData(String url) {
		if (IsNetWork.isNetworkAvalible(getActivity())) {
			mAbPullListView.setVisibility(View.GONE);
			webview.setVisibility(View.VISIBLE);

			// 加载需要显示的网页
			webview.loadUrl(url);
			// 设置Web视图
			webview.setWebViewClient(new HelloWebViewClient());
			webview.setWebChromeClient(new WebChromeClient() {
				public void onProgressChanged(WebView view, int progress) {
					if (progress == 100) {
						stopDialog();
						try {
							mAbPullListView.stopRefresh();
						} catch (Exception e) {
						}
					}
				}
			});
		} else {
			mAbPullListView.setVisibility(View.VISIBLE);
			webview.setVisibility(View.GONE);
			try {
				mAbPullListView.stopRefresh();
			} catch (Exception e) {
			}
		}

	}

	// Web视图
	private class HelloWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			webDispose(view, url);
			return true;
		}

		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			view.stopLoading();
			view.clearView();
			Message msg = handler.obtainMessage();// 发送通知，加入线程
			msg.what = 2;// 通知加载自定义404页面
			handler.sendMessage(msg);// 通知发送！
		}
	}

	protected void webDispose(WebView view, String url) {
		if (!isTelOrQQ(url)) {
			if (!IsNetWork.isNetworkAvalible(getActivity())) {
				mAbPullListView.setVisibility(View.VISIBLE);
				webview.setVisibility(View.GONE);
				try {
					mAbPullListView.stopRefresh();
				} catch (Exception e) {
				}
			} else {
				view.loadUrl(url);
			}
		}
	}

	protected void showWaittingDialog() {
		if (IsNetWork.isNetworkAvalible(getActivity())) {
			mCustDialog = new CustomProgressDialog(getActivity(), "加载中...",
					R.anim.frame_customer);
			mCustDialog.show();
		}
	}

	@OnClick(R.id.img_erweima)
	public void clickTwoCode(View view) {
		Intent intent = new Intent(getActivity(), CaptureActivity.class);
		startActivity(intent);
	}

	protected void stopDialog() {
		// 停止progressDialog
		if (mCustDialog != null) {
			mCustDialog.dismiss();
		}
		
	}

	protected void showShortToast(String msg) {
		Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == FragmentActivity.RESULT_CANCELED) {
			if (null != data) {
				getActivity().finish();
			}
		}
	}

	protected void setBuilder(String title, String msg, Activity baseActivity) {
		mBialog = new Builder(baseActivity);
		mBialog.setTitle(title);
		mBialog.setMessage(msg);
		mBialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				onBuilderExcute();
			}
		});
		mBialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				dialog.dismiss();

			}
		});
		mBialog.show();

	}

	protected void setBuilder(String confirmBtn, String cancelBtn,
			String title, String msg, Activity baseActivity,
			boolean isCancelable) {
		mBialog = new Builder(baseActivity);
		mBialog.setTitle(title);
		mBialog.setMessage(msg);
		mBialog.setCancelable(isCancelable);
		mBialog.setPositiveButton(confirmBtn,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						onBuilderExcute();
					}
				});
		if (cancelBtn != null) {
			mBialog.setNegativeButton(cancelBtn,
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							onBuilderCancel();
							dialog.dismiss();

						}
					});
		}
		mBialog.show();

	}

	protected boolean isTelOrQQ(String url) {
		boolean result = false;
		if (url.startsWith("mailto:") || url.startsWith("geo:")
				|| url.startsWith("tel:") || url.startsWith("mqqwpa:")) {
			if (url.startsWith("mqqwpa:")) {
				if (Tools.isAppInstalled(getActivity(), "com.tencent.mobileqq")) {
					result = true;
				} else {
					Toast.makeText(getActivity(), "当前手机没有安装QQ",
							Toast.LENGTH_SHORT).show();
					return true;
				}
			} else {
				result = true;
			}
			Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
			startActivity(intent);
			return result;
		} else if (url.startsWith("qrcode:")) {
			Intent intent = new Intent(getActivity(), CaptureActivity.class);
			startActivity(intent);
			return true;
		}
		return result;
	}

	protected void onBuilderExcute() {

	}

	protected void onBuilderCancel() {

	}
}
